from system.action import Action
from system.vec2 import Vec2
from system.timeServer import timeServer

class Body(Action):
    def run(self, args):
        timeServer.subscribe(args.get('fps',50),self.update)
        
    def update(self, args):
        time = args['time']
        dtime = args['dtime']
        
        mass = self.object.getVar("mass",1)
        
        force = Vec2(self.object.getVar("force",(0,0)))
        aforce = Vec2(self.object.getVar("alignedForce",(0,0)))
        torque = self.object.getVar("torque",0)
        
        friction = self.object.getVar("friction",0.5)
        rotFriction = self.object.getVar("rotFriction",0.5)
        rot = self.object.getVar("rot",0)
        
        totalForce = force + aforce.rotate(rot)
        acc = totalForce / mass
        vel = (Vec2(self.object.getVar("vel",(0,0))) + acc * dtime) * (1 - friction * dtime)
        pos = Vec2(self.object.getVar("pos",(0,0))) + vel * dtime
        
        rotAcc = torque / mass
        rotVel = (self.object.getVar("rotVel",0) + rotAcc * dtime) * (1 - rotFriction * dtime)
        rot = rot + rotVel * dtime
        
        self.object.setVar("vel",vel.toTuple())
        self.object.setVar("pos",pos.toTuple())
        self.object.setVar("rotVel",rotVel)
        self.object.setVar("rot",rot)
